package com.misssad.repository;

import static com.mongodb.client.model.Filters.eq;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.bson.BsonValue;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Repository;

import com.misssad.model.Girl;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;

@Repository
public class GirlRepository{
	
	private static MongoDatabase db = getDateBase("test");
	
	
	/**
	 * 拿数据库的连接
	 * @param collection
	 * @return
	 */
	public static MongoDatabase getDateBase(String db){
		MongoDatabase database = null;
		try {
			//连接数据库 start
			MongoCredential credential = MongoCredential.createCredential("yutao", db, "yutao".toCharArray());
//			MongoCredential credential = MongoCredential.createMongoCRCredential("yutao", db, "yutao".toCharArray());
			ServerAddress serverAddress;
			serverAddress = new ServerAddress("localhost", 27017);
			List<ServerAddress> addrs = new ArrayList<ServerAddress>();
			addrs.add(serverAddress);
			List<MongoCredential> credentials = new ArrayList<MongoCredential>();
			credentials.add(credential);
//			@SuppressWarnings("resource")
			MongoClient mongoClient = new MongoClient(addrs, credentials);
			database = mongoClient.getDatabase(db);
			System.out.println("Connect to database successfully");
			//连接数据库 end
		} catch (Exception e) {
			System.err.println( e.getClass().getName() + ": " + e.getMessage() );
		}
		return database;
	}
	
	/**
	 * 获取列表
	 * @return
	 */
	public List<Map<String, Object>> findAll() {
		MongoDatabase db = getDateBase("test");
		MongoCollection<Document> collection = db.getCollection("girl");
		/*collection.find().forEach(new Block<Document>() {

			@Override
			public void apply(Document arg0) {
				System.out.println(arg0.toJson());
			}
		});*/
		FindIterable<Document> iterable = collection.find();
		MongoCursor<Document> mongoCursor = iterable.iterator();
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		while(mongoCursor.hasNext()){
			Document o = mongoCursor.next();
			Set<Entry<String,Object>> entrySet = o.entrySet();
			Map<String, Object> map = new HashMap<String, Object>();
			for(Entry<String,Object> es:entrySet){
				String key = es.getKey();
				Object value = es.getValue();
				map.put(key, value.toString());
			}
			result.add(map);
		}
		mongoCursor.close();
		return result;
	}

	/**
	 * 插入一条数据
	 * @param girl
	 * @return
	 */
	public Girl save(Girl girl) {
		
		MongoDatabase db = getDateBase("test");
		MongoCollection<Document> collection = db.getCollection("girl");
		
		Document project = new Document();
		project.append("age", girl.getAge());
		project.append("cupSize", girl.getCupSize());
		
		collection.insertOne(project);
		return girl;
	}

	/**
	 * 
	 * @param id
	 * @return
	 */
	public Document findOne(String id) {
		MongoCollection<Document> collection = db.getCollection("girl");
		ObjectId objectId = new ObjectId(id);
		
		Document document = collection.find(eq(objectId)).first();
		
		return document;
	}

	/**
	 * 更新文档
	 * @param girl
	 * @return
	 */
	public void update(Girl girl) {
		MongoCollection<Document> collection = db.getCollection("girl");
		
		UpdateResult updateOne = collection.updateOne(eq(new ObjectId(girl.getId())),
				new Document("$set", new Document("age", girl.getAge()).append("cupSize", girl.getCupSize())));
		
		long matchedCount = updateOne.getMatchedCount();
		long modifiedCount = updateOne.getModifiedCount();
		BsonValue upsertedId = updateOne.getUpsertedId();
		
		System.out.println(matchedCount + "---" + modifiedCount + "---" + upsertedId);
		
//		UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100));//更新多条记录
//		System.out.println(updateResult.getModifiedCount());
	}

	/**
	 * 删除
	 * @param id
	 */
	public void delete(String id) {
		MongoCollection<Document> collection = db.getCollection("girl");
		
		DeleteResult deleteResult = collection.deleteOne(eq(new ObjectId(id)));
		System.out.println(deleteResult.getDeletedCount());
//		DeleteResult deleteResult = collection.deleteMany(gte("i", 100));
//		System.out.println(deleteResult.getDeletedCount());
		
	}

}
